package com.blog.personalblog.service.Impl;

import com.blog.personalblog.config.page.PageRequest;
import com.blog.personalblog.entity.Category;
import com.blog.personalblog.entity.Tag;
import com.blog.personalblog.mapper.CategoryMapper;
import com.blog.personalblog.mapper.TagMapper;
import com.blog.personalblog.service.CategoryService;
import com.blog.personalblog.service.TagService;
import com.github.pagehelper.PageHelper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Log4j2
@Service
public class TagServiceImpl implements TagService {
    @Autowired
    TagMapper tagMapper;
    @Override
    public List<Tag> getTagPage(PageRequest pageRequest) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum,pageSize);
        List<Tag> tagList = tagMapper.getTagPage();
        return tagList;
    }

    @Override
    public int createTag(Tag tag) {
        return tagMapper.createTag(tag);
    }

    @Override
    public void deleteTag(Integer id) {
        tagMapper.deleteTag(id);
    }

    @Override
    public Tag getTagById(Integer id) {
        Tag tag= tagMapper.getTagById(id);
        return  tag;
    }

    @Override
    public boolean batchAddTag(String tags) throws Exception {
        String[] split = tags.split(",");
        List<Tag> tagList = new ArrayList<>();
        for (String str:split) {
            if (getTagByName(str) == null) {
                Tag tag = new Tag();
                tag.setTagName(str);
                tagList.add(tag);
            }
        }
        if (tagList == null || tagList.size() == 0 || tagList.size() > 10 ){
            throw new Exception("标签已存在或超过标签的限制！");
        }
            boolean isStatus = tagMapper.batchAddTag(tagList);
            return isStatus;
    }

    @Override
    public Tag getTagByName(String tagName) {
        return tagMapper.getTagByName(tagName);
    }

    @Override
    public int updateTag(Tag tag) {
        return tagMapper.updateTag(tag);
    }
}
